package br.edu.ifrn.potigol.lang.nodes;

import br.edu.ifrn.potigol.lang.Context;
import br.edu.ifrn.potigol.lang.PotigolArrayObject;
import br.edu.ifrn.potigol.lang.PotigolException;
import br.edu.ifrn.potigol.lang.PotigolObject;
import br.edu.ifrn.potigol.lang.PotigolRuntime;
import br.edu.ifrn.potigol.lang.ValueObject;

public class ForEachNode extends Node {
	private String name;
	private Node firstValue;
	private Node lastValue;
	private ArrayNode collection;
	private Node body;
	private boolean range = false;
	
	public ForEachNode(String name, ArrayNode collection, Node body) {
		this.name = name;
		this.collection = collection;
		this.body = body;
	}
	
	public ForEachNode(String name, Node firstValue, Node lastValue, Node body) {
		this.name = name;
		this.firstValue = firstValue;
		this.lastValue = lastValue;
		this.body = body;
		range = true;
	}

	public PotigolObject eval(Context context) throws PotigolException {
		context.createLocal(name, PotigolRuntime.getNil());		
		
		if (range) {
			
			Integer f = firstValue.eval(context).asInteger();			
			Integer l = lastValue.eval(context).asInteger();
			
			for (int i=f; i <= l; ++i) {
				context.setLocal(name, new ValueObject(i));
				body.eval(context);
			}
		} else {
			PotigolArrayObject potigolArrayObject = context.getArray(collection.getName());
			PotigolObject[] arrayObject = potigolArrayObject.getArray();
			
			for (int i=0; i < arrayObject.length; ++i) {
				context.setLocal(name, arrayObject[i]);
				body.eval(context);
			}
		}
		
		return PotigolRuntime.getNil();
	}
}
